package com.myk.game.heroscuffle.ui;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.myk.game.heroscuffle.R;
import com.myk.game.heroscuffle.data.GameParam;
import com.myk.game.heroscuffle.data.GameTextData;
import com.myk.game.heroscuffle.game.Game;
import com.myk.game.heroscuffle.game.GameUI;
import com.myk.game.heroscuffle.utils.ShareUtil;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;


public class MainActivity extends AppCompatActivity implements GameUI {

    private Game mGame;
    private GameMsgLayout gameMsgLayout;
    private GameCtrlLayout gameCtrlLayout;
    private Context mContext;
    private Handler mHandler;
    private SimpleDateFormat mDateFormat;
    private String mRecordPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        hideActionBar();

        mContext = this;
        mHandler = new Handler(Looper.getMainLooper());

        mDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
        mRecordPath = PathUtils.getExternalAppDataPath() + "/record/";

        gameMsgLayout = findViewById(R.id.gml_main_msg);
        gameCtrlLayout = findViewById(R.id.gml_main_ctrl);

        mGame = new Game(this);
        mGame.initHome();
    }


    @Override
    public void showHelpDialog() {
        new AlertDialog.Builder(this).setMessage(GameTextData.GAME_RULE).setCancelable(true).setPositiveButton("关闭", (dialog, which) -> dialog.dismiss()).show().setCanceledOnTouchOutside(true);
    }

    @Override
    public void showRecordDialog() {
        mHandler.post(() -> {
            List<File> recordFiles = FileUtils.listFilesInDir(mRecordPath);
            String[] fileNames = new String[recordFiles.size()];
            for (int i = 0; i < recordFiles.size(); i++) {
                File recordFile = recordFiles.get(i);
                fileNames[i] = recordFile.getName();
            }
            new AlertDialog.Builder(mContext)
                    .setTitle("英雄乱斗游戏战报列表")
                    .setItems(fileNames, (dialog, which) -> {
                        File recordFile = recordFiles.get(which);
                        String recordData = FileIOUtils.readFile2String(recordFile);
                        new AlertDialog.Builder(this)
                                .setMessage(recordData)
                                .setCancelable(true)
                                .setNeutralButton("删除", (dialog14, which14) -> new android.app.AlertDialog.Builder(this)
                                        .setMessage("是否删除该战报？")
                                        .setNegativeButton("取消", (dialog16, which16) -> dialog16.dismiss())
                                        .setPositiveButton("确定", (dialog15, which15) -> FileUtils.delete(recordFile))
                                        .show())
                                .setNegativeButton("分享", (dialog13, which13) -> ShareUtil.shareFile(mContext, recordFile))
                                .setPositiveButton("关闭", (dialog12, which12) -> dialog12.dismiss())
                                .show();
                    })
                    .setNegativeButton("清空", (dialog, which) -> {
                        for (File recordFile : recordFiles) {
                            FileUtils.delete(recordFile);
                        }
                        dialog.dismiss();
                        ToastUtils.showShort("游戏战报已清空！");
                    })
                    .setPositiveButton("关闭", (dialog1, which1) -> dialog1.dismiss())
                    .show();
        });
    }

    @Override
    public void showErrorDialog(String errInfo) {
        mHandler.post(() -> new AlertDialog.Builder(mContext)
                .setTitle("游戏流程发生异常")
                .setMessage(errInfo)
                .setCancelable(false)
                .setPositiveButton("回到首页", (dialog, which) -> mGame.initHome())
                .show());
    }

    @Override
    public void showLargeTextDialog(String title,String info) {
        mHandler.post(() -> new AlertDialog.Builder(mContext)
                .setTitle(title)
                .setMessage(info)
                .setCancelable(true)
                .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                .show());
    }

    @Override
    public void saveRecordData() {
        mHandler.post(() -> {
            String fileName = "英雄乱斗游戏战报(v" + AppUtils.getAppVersionName() + ")" + TimeUtils.getNowString(mDateFormat) + ".txt";
            String gameData = gameMsgLayout.getGameMsg();
            FileUtils.createOrExistsDir(mRecordPath);
            boolean saveSuccess = FileIOUtils.writeFileFromString(mRecordPath + fileName, gameData);
            ToastUtils.showShort(saveSuccess ? "战报保存成功！" : "战报保存失败！");
            this.setTip("请选择您的操作...");
            this.resetCtrl();
            this.addCtrl("返回首页", mGame::initHome);
        });
    }

    @Override
    public void saveErrorRecordData(String errInfo) {
        String fileName = "英雄乱斗游戏异常报告(v" + AppUtils.getAppVersionName() + ")" + TimeUtils.getNowString(mDateFormat) + ".txt";
        String gameData = gameMsgLayout.getGameMsg();
        String errData = "\n此处发生异常\n" + errInfo;
        FileUtils.createOrExistsDir(mRecordPath);
        FileIOUtils.writeFileFromString(mRecordPath + fileName, gameData + errData);
    }

    @Override
    public void printMsg(String msg) {
        mHandler.post(() -> gameMsgLayout.addMsg(msg));
    }

    @Override
    public void printlnMsg(String msg) {
        mHandler.post(() -> gameMsgLayout.addMsg("\n" + msg));
    }

    @Override
    public void setTip(String tip) {
        mHandler.post(() -> gameMsgLayout.setTip(tip));
    }

    @Override
    public void clearMsg() {
        mHandler.post(() -> gameMsgLayout.clearMsg());
    }

    @Override
    public void resetCtrl() {
        mHandler.post(() -> gameCtrlLayout.resetAllButtons());
    }

    @Override
    public void addCtrl(String title, Runnable action) {
        mHandler.post(() -> gameCtrlLayout.addButton(title, action));
    }

    @Override
    public void addCtrl(String title, boolean usable, Runnable action) {
        mHandler.post(() -> gameCtrlLayout.addButton(title, usable, action));
    }

    @Override
    public void toast(String text) {
        mHandler.post(() -> Toast.makeText(this, text, Toast.LENGTH_SHORT).show());
    }

    @Override
    public void sleepShortly() {
        if (GameParam.TEXT_SLEEP_SWITCH) {
            SystemClock.sleep(80);
        }
    }

    @Override
    public void sleepFast() {
        if (GameParam.TEXT_SLEEP_SWITCH) {
            SystemClock.sleep(250);
        }
    }

    @Override
    public void sleepNormal() {
        if (GameParam.TEXT_SLEEP_SWITCH) {
            SystemClock.sleep(500);
        }
    }

    @Override
    public void exitApp() {
        finish();
        System.exit(0);
    }

    //隐藏ActionBar
    private void hideActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
    }


}
